<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="1200" destroy-on-close @closed="$emit('closed')" :align-center="true" :close-on-click-modal="false">
        <el-container>
            <el-main>
                <el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="110px" label-position="right" style="height:550px;overflow:auto">
                    <el-row :gutter="1" >
                        <el-col :span="12">
                            <el-form-item label="物料类别" prop="category_id">
                                <el-select v-model="form.category_id" placeholder="请选择" style="width:100%" @change="change">
                                    <el-option label="毛料" :value="1"></el-option>
                                    <el-option label="辅料" :value="2"></el-option>
                                    <el-option label="其他" :value="3"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="物料名称" prop="material_id">
                                <el-select v-model="form.material_id"  filterable style="width: 100%" placeholder="请选择物料名称" @change="nameChange">
                                    <el-option v-for="item in materialList" :key="item.id" :label="item.material_name" :value="item.id"/>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="1" >
                        <el-col :span="12">
                            <el-form-item label="计量单位" prop="unit">
                                <el-select v-model="form.unit"  filterable style="width: 100%" placeholder="请选择计量单位">
                                    <el-option v-for="item in unitArray" :key="item.id" :label="item.unit_name" :value="item.id"/>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="损耗" prop="loss_ratio">
                                <el-input v-model="form.loss_ratio" placeholder="请输入" clearable type="number" @mousewheel.prevent></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="1" >
                        <!-- <el-col :span="12" v-if="factory==0"> -->
                        <el-col :span="12">
                            <el-form-item label="供应商" prop="supplier_id">
                                <el-select v-model="form.supplier_id"  filterable style="width: 100%" placeholder="请选择供应商" @change="supplierChange">
                                    <el-option v-for="item in apply" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"/>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="成分" prop="component">
                                <!-- <el-input v-model="form.component" placeholder="请输入" clearable></el-input> -->
                                <el-select v-model="form.component"  filterable style="width: 100%" placeholder="请选择成分">
                                    <el-option v-for="item in comList" :key="item.id" :label="item.component_name" :value="item.id"/>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="SKU" prop="sku">
                                <el-input v-model="form.sku" placeholder="请输入sku" clearable readonly></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="参考价" prop="reference_price">
                                <el-input v-model="form.reference_price" placeholder="请输入参考价" clearable @change="input" type="number" @mousewheel.prevent></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="1" >
                        <el-col :span="12">
                            <el-form-item label="是否禁用" prop="system_disable">
                                <el-switch v-model="form.system_disable" :active-value="1" :inactive-value="0"></el-switch>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-col>
                        <!-- <el-form-item label="描述" prop="describe">
                            <el-input v-model="form.describe" placeholder="请输入" clearable type="textarea"></el-input>
                        </el-form-item> -->
                        <el-form-item label="上传封面图" prop="image">
                            <sc-upload v-model="form.image" draggable ></sc-upload>
                        </el-form-item>
                    </el-col>
                    <el-row :gutter="1">
                        <sc-form-table ref="table" v-model="form.colour_data" :addTemplate="addTemplate" placeholder="暂无数据" @son="rowAdd" hideDelete>
                            <el-table-column align="center" width="50">
                                <template #default="scope">
                                    <el-button v-if="factory==0 || !scope.row.id" type="danger" icon="el-icon-delete" size="small" plain circle @click="del(scope.$index)"></el-button>
                                </template>
                            </el-table-column>
                            <el-table-column prop="skc" label="物料SKC " align="center" width="220">
                                <template #default="scope">
                                    <el-input v-model="scope.row.skc" placeholder="请输入物料SKC" readonly></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="color_number" label="色号" align="center">
                                <template #default="scope">
                                    <el-input v-model="scope.row.color_number" placeholder="请输入色号"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="colour" label="颜色" align="center">
                                <template #default="scope">
                                    <el-input v-model="scope.row.colour" placeholder="请输入颜色"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="price" label="参考价" align="center">
                                <template #default="scope">
                                    <el-input v-model="scope.row.price" placeholder="请输入参考价" type="number" @mousewheel.prevent></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="image" label="图片" align="center">
                                <template #default="scope">
                                    <sc-upload v-model="scope.row.image" :data="{ otherData: 'demo' }" style="width:40px;height:40px;margin-left:40px" preview-teleported="true">
                                        <el-icon size="24"><el-icon-Plus /></el-icon>
                                    </sc-upload>
                                </template>
                            </el-table-column>
                            <el-table-column prop="remark" label="备注" align="center">
                                <template #default="scope">
                                    <el-input v-model="scope.row.remark" placeholder="请输入内容"></el-input>
                                </template>
                            </el-table-column>
                        </sc-form-table>
                    </el-row>
                </el-form>
            </el-main>
            <el-footer>
                <div style="display:flex;justify-content: end;">
                    <el-button @click="visible=false" >取 消</el-button>
			        <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">确 定</el-button>
                </div>
            </el-footer>
        </el-container>
	</el-dialog>
</template>

<script>
import { defineAsyncComponent } from 'vue';
const scEditor = defineAsyncComponent(() => import('@/components/scEditor'));
	export default {
		components: {
			scEditor
		},
		emits: ['success', 'closed'],
		data() {
			return {
				mode: "add",
				titleMap: {
					add: '添加物料',
					edit: '编辑物料',
					show: '查看'
				},
				visible: false,
				isSaveing: false,
                grade:"潜力",
				//表单数据
				form: {
                    id:"",
					category_id: "",
					material_id:"",
					unit: "",
                    loss_ratio:"",
					sku: "",
                    reference_price:"",
                    // supplier_id:"",
					describe: "",
                    image:"",
					system_disable:0,
                    component:"",
                    colour_data:[],
				},
                addTemplate: {
					color_number:"",
                    color:"",
                    price:"",
                    image:"",
                    remark:"",
                    skc:""
				},
				//验证规则
				rules: {
					material_id: [
						{required: true, message: '请选择'}
					],
					category_id: [
						{required: true, message: '请选择'}
					],
                    supplier_id: [
						{required: true, message: '请选择供应商'}
					],
				},
                apply:[],//供应商
                unitArray:[],   //单位
                comList:[],
                materialList:[],
                compamy:"",
                last:"",
                materName:"",
                // number:1,
                // wuSkcNumber:1
                factory:this.$TOOL.data.get("USER_INFO").factory_id,
                lastNumber:"",
                len:"",
                i:0,
			}
		},
		mounted() {
            this.getUnit()
            this.getsku()
            this.getCom()
		},
		methods: {
			//显示
			open(mode='add'){
				this.mode = mode;
				this.visible = true;
				return this
			},
			//表单提交方法
			submit(){
                console.log('this.form :>> ', this.form);
				this.$refs.dialogForm.validate(async (valid) => {
					if (valid) {
						this.isSaveing = true;
						var res  = [];
						if (this.form.id) {
							res = await this.$API.material.getSupplierList.edit.post(this.form);
						}else{
							res = await this.$API.material.getSupplierList.add.post(this.form);
						}
						this.isSaveing = false;
						if(res.code == 1){
							this.$emit('success', this.form, this.mode)
							this.visible = false;
							this.$message.success("操作成功")
						}else{
							this.$alert(res.message, "提示", {type: 'error'})
						}
					}else{
						return false;
					}
				})
			},
			//表单注入数据
			async setData(data){
                this.form.id = data.id
                var res = await this.$API.material.getSupplierList.detail.get({id:data.id});
                let array = []
                res.data.materialSpec.map(item=>{
                    array.push({
                        id:item.id,
                        color_number:item.color_number,
                        colour:item.colour,
                        skc:item.skc,
                        price:item.price,
                        image:item.image,
                        component:item.component,
                        remark:item.remark
                    })
                })
                this.lastNumber = array.length-1
                this.len = array.length
                this.form.colour_data = array
                this.form.category_id = res.data.category_id
                this.form.material_id = res.data.material_id
                this.form.supplier_id = res.data.supplier_id
                this.form.reference_price = res.data.reference_price
                this.form.sku = res.data.sku
                this.form.loss_ratio = res.data.loss_ratio
                this.form.component = res.data.component==0?"":Number(res.data.component)
                // this.form.describe = res.data.describe
                this.form.image = res.data.image
                this.form.system_disable = res.data.system_disable
                this.form.unit = Number(res.data.unit)
                var e = await this.$API.all.material.get({category_id:res.data.category_id});
                this.materialList = e.data;
                e.data.map((item)=>{
                    if(res.data.material_id == item.id){
                        this.materName = item.material_name_pinyin
                    }
                })
                if(res.data.category_id==1){
                    var a = await this.$API.all.Apply.get({type:3});
				    this.apply = a.data;
                }else if(res.data.category_id==2){
                    var b = await this.$API.all.Apply.get({type:4});
				    this.apply = b.data;
                }
                this.getsku(res.data.supplier_id)
			},
            async getsku(e){
                var res = await this.$API.material.getSKU.get({supplier_id:e});
                this.compamy = res.data.company_abbr
                this.last = res.data.last_code
                if(this.form.category_id!='' && this.form.material_id!='' && this.form.supplier_id!=''){
                    this.form.sku = res.data.company_abbr + this.materName + res.data.last_code
                }
            },
            // 获取单位
            async getUnit(){
				var res = await this.$API.all.unit.get();
				this.unitArray = res.data;
			},
            // 获取成分
            async getCom(){
				var res = await this.$API.all.component.get();
				this.comList = res.data;
			},
            // 切换类别获取名称
            async change(e){
                this.form.supplier_id = ''
                this.form.material_id = ''
                this.form.sku = ''
                var res = await this.$API.all.material.get({category_id:e});
                this.materialList = res.data;
                if(e==1){
                    var a = await this.$API.all.Apply.get({type:3});
				    this.apply = a.data;
                }else if(e==2){
                    var data = await this.$API.all.Apply.get({type:4});
				    this.apply = data.data;
                }
            },
            nameChange(e){
                this.materialList.map((item)=>{
                    if(e == item.id){
                        this.materName = item.material_name_pinyin
                        if(this.form.category_id!='' && this.form.material_id!='' && this.form.supplier_id!=''){
                            this.form.sku = this.compamy + this.materName + this.last
                        }
                    }
                })
            },
            supplierChange(e){
                this.getsku(e)
            },
            rowAdd(){
                if(this.mode=='add'){
                    this.form.colour_data.map((item,index)=>{
                        let wuSkcNumber =  ('00' + (index+1)).slice(-3);
                        this.form.colour_data[index].skc = this.compamy + this.materName + this.last + wuSkcNumber;
                        this.form.colour_data[index].price = this.form.reference_price;
                    })
                }else{
                    let skc = this.form.colour_data[this.lastNumber].skc;
                    let indexNum = this.len++;
                    this.i++
                    let lastThreeDigits = skc.substr(-3);
                    let num = '';
                    let lastThreeDigitsInt = parseInt(lastThreeDigits);
                    let newLastThreeDigits = String((lastThreeDigitsInt + this.i) % 1000);
                    num = lastThreeDigits.substring(0, lastThreeDigits.length - 3) + newLastThreeDigits.padStart(3, '0');
                    this.form.colour_data[indexNum].skc = this.compamy + this.materName + this.last + num;
                    this.form.colour_data.map((item,index)=>{
                        console.log(index);
                        this.form.colour_data[indexNum].price = this.form.reference_price;
                    })
                }
            },
            del(index1){
                this.form.colour_data.splice(index1,1)
                if(this.mode == 'add'){
                    this.form.colour_data.map((item,index)=>{
                        let wuSkcNumber =  ('00' + (index+1)).slice(-3);
                        this.form.colour_data[index].skc = this.compamy + this.materName + this.last + wuSkcNumber;
                    })
                }else{
                    this.len--
                }
            },
            input(){
                this.form.colour_data.map((item,index)=>{
                    console.log('item :>> ', item);
                    if(item.price=='' || item.price==0){
                        this.form.colour_data[index].price = this.form.reference_price;
                    }
                })
            },
		}
	}
</script>

<style lang="scss">
.el-form-item--default{
    align-items: center;
}
</style>
